#include "ApplicationException.h"

#include "platform.h"

#include <stdexcept>
#include <string>
using namespace std;

static string w2a(const wstring& text)
{
	int nbytes = WideCharToMultiByte( 
		CP_UTF8, // specify the code page used to perform the conversion
		0,         // no special flags to handle unmapped characters
		text.c_str(),     // wide character string to convert
		text.length(),   // the number of wide characters in that string
		NULL,      // no output buffer given, we just want to know how long it needs to be
		0,
		NULL,      // no replacement character given
		NULL );    // we don't want to know if a character didn't make it through the translation

	// make sure the buffer is big enough for this, making it larger if necessary
	if(!nbytes)
		throw runtime_error("w2a failed; no sufficient memory");

	char* buff = new char[nbytes];

	WideCharToMultiByte( 
		CP_UTF8, // specify the code page used to perform the conversion
		0,         // no special flags to handle unmapped characters
		text.c_str(),   // wide character string to convert
		text.length(),   // the number of wide characters in that string
		buff, // put the output ascii characters at the end of the buffer
		nbytes,                           // there is at least this much space there
		NULL,      // no replacement character given
		NULL );

	string ansi(buff, nbytes);
	delete[] buff;

	return ansi;
}

ApplicationException::ApplicationException(const wstring& message)
	: runtime_error(w2a(message))
{
}


